#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: processname ip port" << std::endl;
        return 1;
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    // 开始创建tcp套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "Socket failed" << std::endl;
        exit(1);
    }

    // 和服务端建立连接,需要sockaddr_in来表示目标地址，记得将主机属性转网络属性
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_port = htons(port);
    addr.sin_family = AF_INET;
    inet_pton(AF_INET, ip.c_str(), &addr.sin_addr.s_addr);

    if (connect(sockfd, (sockaddr *)&addr, sizeof(addr)) < 0)
    {
        std::cout << "connect error" << std::endl;
        return 0;
    }

    // connect 连接成功，可以使用sockfd与服务端进行通信了。
    while (true)
    {
        // 接收数据
        std::cout << "Please enter:";
        std:: string message;
        getline(std::cin, message);

        // 发送数据
        ssize_t n = send(sockfd, message.c_str(), message.size(), 0);
        if(n > 0)
        {
            // 发送成功,准备接收数据。
            char buffer[1024];
            ssize_t m = recv(sockfd, buffer, sizeof(buffer), 0);

            if(m > 0)
            {
                // 接收成功
                buffer[m] = 0;
                std::string resp = buffer;
                std::cout << resp << std::endl;
            }
            else
            {
                std::cout << "Recv failed" << std::endl;
                exit(1);
            }
        }
        else
        {
            std::cout << "Send message failed" << std::endl;
        }
    }
    
    close(sockfd);

    return 0;
}